package com.elite.groovy.callback

import com.elite.groovy.kh.KHDBConfig
import com.elite.groovy.kh.KHUtil
import com.elite.groovy.util.EliteBean
import com.elite.groovy.util.IpAddressUtil
import net.sf.json.JSONArray
import net.sf.json.JSONObject
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.springframework.jdbc.core.JdbcTemplate
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import java.util.regex.Matcher
import java.util.regex.Pattern

public class apiCXCheckTools implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(apiCXCheckTools.class);
    private static JdbcTemplate jt = new JdbcTemplate();
    private static String s_DB_Type = "oracle";
    private static long startTime = System.currentTimeMillis();

    private static String Dynid = "";
    private static String Dynid2 = "";
    private static String Dynname = "";
    private static String Dyntype = "";
    private static String Dyn_Pageid = "";
    private static String Dyn_CtlId = "";
    private static String Dyn_CtlName = "";
    private static String Dyn_SQLId = "";

    private static Map<String, String> SQL_DSL_Map = new HashMap<String, String>();

    // DYN SQL情况检查
    private static String upd_SQL = "Update xc_dyn_sql_check Set Dyn_Id = ?, Dynname = ?, Dyntype = ?, Sql_Type = ?, Sql_Json = ?, Check_Sql = ?, Check_Result = ?, Check_Status = ?, DB_Type = ?, DYN_Page_ID = ?, Dyn_CtlId = ?, Dyn_CtlName = ?, SQL_Id = ?, Check_Cost = ? Where Dynid2 = ? And Sql_Md5 = ?";
    private static String log_SQL = "Insert Into xc_dyn_sql_check (Check_Guid, Dyn_Id, Dynid2, Dynname, Dyntype, Sql_Md5, Sql_Type, Sql_Json, Check_Sql, Check_Result, Check_Status, DB_Type, DYN_Page_ID, Dyn_CtlId, Dyn_CtlName, SQL_Id, Check_Cost) Values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

    // DYN 组件情况检查
    private static String comp_Upd_SQL = "Update xc_dyn_components Set Dyn_Id = ?, Dynname = ?, Dyntype = ?, Dyn_Page_Id = ?, Comp_Dynname = ? Where Dynid2 = ? And Comp_Dynid2 = ?";
    private static String comp_Log_SQL = "Insert Into xc_dyn_components (Check_Guid, Dyn_Id, Dynid2, Dynname, Dyntype, Dyn_Page_Id, Comp_Dynid2, Comp_Dynname) Values (?, ?, ?, ?, ?, ?, ?, ?)";

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        long startTime = System.currentTimeMillis();
        JSONObject outData = JSONObject.fromObject("{\"code\":1,\"message\":\"操作成功\"}");

        // 调用IP过滤
        if (KHDBConfig.getParam(eliteBean, "#APIIP") == "1" && !KHUtil.getRemoteHost(request)) {
            outData.put("code", -1);
            outData.put("message", "API被非法IP调用-Request Not Allow!" + IpAddressUtil.getIpAddress(request));
            log.warn(outData);
            return outData;
        }

        String getMethod = request.getMethod();
        log.debug("HTTP请求调用类型 getMethod:" + getMethod);
        if (getMethod != "GET") {
            outData.put("code", -1);
            outData.put("message", "HTTP请求调用类型错误，接口调用失败：" + getMethod);
            log.error(outData);
            return outData;
        }

        // 获取所有Header
        Map<String, String> mapHeader = new HashMap<String, String>();
        Enumeration headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String key = (String) headerNames.nextElement();
            String value = request.getHeader(key);
            log.debug("Call Header-" + key + ":" + value);

            mapHeader.put(key, value);
        }

        // 获取所有参数名
        Map<String, String> mapParam = new HashMap<String, String>();
        Enumeration ep = request.getParameterNames();
        while (ep.hasMoreElements()) {
            String key = (String) ep.nextElement();
            String value = request.getParameter(key);
            log.debug("Call Parameter-" + key + ":" + value);
            mapParam.put(key, value);

        }

        // 获取数据源List<Map<String, Object>>
        jt = new JdbcTemplate(eliteBean.getDataSource());

        try {
            // 解析请求报文
            String dynid2 = request.getParameter("dynid2");
            log.debug("指定处理的DYNID2(为空则为所有DYN)：" + dynid2);

            doCheckDyn(dynid2);

        } catch (Exception e) {
            outData.put("code", -1);
            outData.put("message", "HTTP请求调用错误，接口处理异常：" + e.getMessage());
            log.error(outData, e);

        }
        return outData;
    }

    // CheckDyn-SQL
    public static void doCheckDyn(String in_Dynid2) {

        List<Map<String, Object>> selectDYNs = new ArrayList<>();
        if (!KHUtil.isNull(in_Dynid2)) {
            String getDYN_Info = "Select Td.Dynid, Td.Dynid2, Td.Dynname, Td.Dyntype, Td.Content As Td_Content, Tds.Content As Tds_Content From Tab_Dyn Td Left Join Tab_Dyn_Sqls Tds On Tds.Dynid = Td.Dynid Where Td.Removed = 0 And Td.Dynid2 = ? Order By Td.Dyntype, Td.Dynid2, Td.Dynname";
            selectDYNs = jt.queryForList(getDYN_Info, in_Dynid2);

        } else {
            String getDYN_Info = "Select Td.Dynid, Td.Dynid2, Td.Dynname, Td.Dyntype, Td.Content As Td_Content, Tds.Content As Tds_Content From Tab_Dyn Td Left Join Tab_Dyn_Sqls Tds On Tds.Dynid = Td.Dynid Where Td.Removed = 0 Order By Td.Dyntype, Td.Dynid2, Td.Dynname";
            selectDYNs = jt.queryForList(getDYN_Info);
        }
        int Dyn_Num = selectDYNs.size();
        log.debug("DYN_SQL-获取所有动态页面 数量 :" + selectDYNs.size());

        // 处理节点数据
        int loop_Num = 0;
        for (Map<String, Object> DYNMap : selectDYNs) {
            loop_Num++;
            Dynid = KHUtil.GetMapV(DYNMap, "Dynid");
            Dynid2 = KHUtil.GetMapV(DYNMap, "Dynid2");
            Dynname = KHUtil.GetMapV(DYNMap, "Dynname");
            Dyntype = KHUtil.GetMapV(DYNMap, "Dyntype");
            Dyn_Pageid = "/";
            String Td_Content = KHUtil.GetMapV(DYNMap, "Td_Content");
            String Tds_Content = KHUtil.GetMapV(DYNMap, "Tds_Content");
            log.debug("ℹ-(" + loop_Num + "/" + Dyn_Num + ")获取主页面 Dynid2:" + Dynid2 + " Dynname:" + Dynname);
            SQL_DSL_Map.clear();

            // 1-主页面Content中SQL处理
            analysisDynSQL(Td_Content, Tds_Content);

            // 2-分页面Content中SQL处理
            List<Map<String, Object>> selectPages = jt.queryForList("Select Tdp.Pageid, Tdp.Content As Tdp_Content From Tab_Dyn_Page Tdp Where Tdp.Dynid = ? Order By Tdp.Pageid", Dynid);
            int DynPage_Num = selectPages.size();
            log.debug("DYN_SQL-获取动态页面所有Page 数量 :" + DynPage_Num);

            // 处理节点数据
            int loopPage_Num = 0;
            for (Map<String, Object> DYNPageMap : selectPages) {
                loopPage_Num++;
                Dyn_Pageid = KHUtil.GetMapV(DYNPageMap, "Pageid");
                String Tdp_Content = KHUtil.GetMapV(DYNPageMap, "Tdp_Content");
                log.debug("ℹ-(" + loopPage_Num + "/" + DynPage_Num + " " + loop_Num + "/" + Dyn_Num + ")获取分页面 Dynid2:" + Dynid2 + " Dynname:" + Dynname + " Pageid:" + Dyn_Pageid);

                analysisDynSQL(Tdp_Content, Tds_Content);
            }

        }

    }

    // 分析页面Main
    public static String analysisDynSQL(String Tdp_Content, String Tds_Content) {

        // 页面Content异常直接跳过忽略处理
        if (KHUtil.SFIsNull(Tds_Content)) {
            log.warn("⛔-页面Content异常直接跳过忽略处理 Dynid2:" + Dynid2 + " Dynname:" + Dynname + " Pageid:" + Dyn_Pageid + " Content:" + Tds_Content);
            return "";
        }

        JSONObject in_Json = JSONObject.fromObject(Tdp_Content);
        JSONObject re_Json = JSONObject.fromObject(Tdp_Content);

        // 识别clearDsl, 如果存在则将SQL片段清理
        if (KHUtil.GetSFJV(in_Json, "type").equals("900")) {
            List<String> res_SQLDSLs = get_ClearDSLs(KHUtil.GetSFJV(in_Json, "content"), "");

            for (int i = 0; i < res_SQLDSLs.size(); i++) {
                String dsl_Key = res_SQLDSLs.get(i).replace("clearDsl('", "").replace("'", "");
                SQL_DSL_Map.remove(dsl_Key);
                log.debug("♻-数据库操作-将SQL片段清理-SQLDSL clearDsl：" + dsl_Key);

            }
        }

        // 判断是否是SQL类型 902 动态页面-数据库操作
        if (KHUtil.GetSFJV(in_Json, "type").equals("902")) {

            JSONObject sql_Content = in_Json.getJSONObject("content");
            String sql_Type = KHUtil.GetSFJV(sql_Content, "sub"); // SQL命令类型 0 标准/1 执行事务/2 条件片段/3 存储过程
            String sql_bExe = KHUtil.GetSFJV(sql_Content, "exe", "0"); // 执行事务类型 1 批量更新/其他 批量查询
            String sql_pKey = KHUtil.GetSFJV(sql_Content, "key"); // 片段类名
            String sql_pNum = KHUtil.GetSFJV(sql_Content, "num"); // 片段序号
            String sql_SQLID = KHUtil.GetSFJV(sql_Content, "sql"); // SQL片段
            String sql_SQLs = KHUtil.GetSFJV(sql_Content, "sqls"); // SQL集合
            String sql_Params = KHUtil.GetSFJV(sql_Content, "params"); // SQL参数集合
            String sql_DBType = KHUtil.GetSFJV(sql_Content, "type", s_DB_Type); // SQL数据库类型

            // SQL命令类型
            log.debug("✅动态页面-数据库操作-sql_Type：" + sql_Type + " sql_bExe:" + sql_bExe + " Tdp_Content:" + Tdp_Content);

            // 根据类型处理SQL
            if (sql_Type.equals("0")) { // 标准
                String SQLPart = getSQLPart(sql_SQLID, Tds_Content);
                log.debug("Ⓜ-数据库操作-标准-SQLPart：" + SQLPart);

                doSQLRunCheck("标准", SQLPart, sql_pKey, sql_DBType);

            } else if (sql_Type.equals("1")) { // 执行事务
                if (sql_bExe.equals("0")) { // 批量查询
                    JSONArray SQLs_Arr = JSONArray.fromObject(sql_SQLs);
                    String SQLPart = "";

                    for (int i = 0; i < SQLs_Arr.size(); i++) {
                        String tmp_SQLID = KHUtil.GetSFJV(SQLs_Arr.getJSONObject(i), "sql");
                        SQLPart = getSQLPart(tmp_SQLID, Tds_Content);
                        log.debug("Ⓜ-数据库操作-执行事务-批量查询-SQLPart：" + SQLPart);
                        doSQLRunCheck("批量查询", SQLPart, sql_pKey, sql_DBType);
                    }

                } else if (sql_bExe.equals("1")) { // 批量更新
                    JSONArray SQLs_Arr = JSONArray.fromObject(sql_SQLs);
                    String SQLPart = "";

                    for (int i = 0; i < SQLs_Arr.size(); i++) {
                        String tmp_SQLID = KHUtil.GetSFJV(SQLs_Arr.getJSONObject(i), "sql");
                        SQLPart = getSQLPart(tmp_SQLID, Tds_Content);
                        log.debug("Ⓜ-数据库操作-执行事务-批量更新-SQLPart：" + SQLPart);
                        doSQLRunCheck("批量更新", SQLPart, sql_pKey, sql_DBType);
                    }

                } else {
                    log.warn("-数据库操作-执行事务-未知批量的类型,请检查处理逻辑⛔");
                }

            } else if (sql_Type.equals("2")) {
                // 获取SQL片段类名对应的已有SQL片段
                String sql_PartStr = KHUtil.GetMapV(SQL_DSL_Map, sql_pKey + "_" + sql_pNum);
                String SQLPart = getSQLPart(sql_SQLID, Tds_Content);

                sql_PartStr = sql_PartStr + SQLPart + " ";

                // 将获取的查询片段放回SQL_DSL_Map 以便查询时检查使用
                SQL_DSL_Map.put(sql_pKey + "_" + sql_pNum, sql_PartStr);
                log.debug("➡-数据库操作-条件片段-SQLPart：" + SQLPart);

            } else if (sql_Type.equals("3")) {
                String SQLPart = "call " + KHUtil.GetSFJV(sql_Content, "name") + "(";

                JSONArray Params_Arr = JSONArray.fromObject(sql_Params);
                // 拼接存储过程参数
                for (int i = 0; i < Params_Arr.size(); i++) {
                    String param_Key = KHUtil.GetSFJV(Params_Arr.getJSONObject(i), "key");
                    String param_Value = KHUtil.GetSFJV(Params_Arr.getJSONObject(i), "value");
                    SQLPart = SQLPart + (i == 0 ? "" : ",") + param_Value;
                }
                SQLPart = SQLPart + ")";
                log.debug("☢-数据库操作-存储过程-SQLPart：" + SQLPart);
                doSQLRunCheck("存储过程", SQLPart, "", sql_DBType);

            } else {
                log.warn("未知SQL类型-请检查处理逻辑⛔");
            }
        } else {
            // 循环Loop
            Set<String> keySet = in_Json.keySet();
            for (String key : keySet) {
                Object obj = in_Json.get(key);

                // 根据类型识别是否继续递归
                if (obj instanceof JSONArray) { // 数组
                    JSONArray arr = (JSONArray) obj;
                    for (int i = 0; i < arr.size(); i++) {
                        if (arr.get(i) instanceof JSONObject) {

                            // 检查当前对象中是否包含id(控件ID或命令ID),只更新为最后一个
                            Dyn_CtlId = in_Json.containsKey("id") ? KHUtil.GetSFJV(in_Json, "id") : Dyn_CtlId;
                            Dyn_CtlName = in_Json.containsKey("name") ? KHUtil.GetSFJV(in_Json, "name") : Dyn_CtlName;

                            analysisDynSQL(arr.get(i).toString(), Tds_Content);
                        } else {
                            // log.debug("Json数据-key：" + key + " 值JSONArray 单个循环非JSONObject");

                        }
                    }
                } else if (obj instanceof JSONObject) { // 对象
                    JSONObject sub = (JSONObject) obj;

                    // 检查当前对象中是否包含id(控件ID或命令ID),只更新为最后一个
                    Dyn_CtlId = in_Json.containsKey("id") ? KHUtil.GetSFJV(in_Json, "id") : Dyn_CtlId;
                    Dyn_CtlName = in_Json.containsKey("name") ? KHUtil.GetSFJV(in_Json, "name") : Dyn_CtlName;

                    analysisDynSQL(sub.toString(), Tds_Content);
                } else if (key.equals("sql")) { // SQL

                    String sql_SQLID = obj.toString();
                    String SQLPart = getSQLPart(sql_SQLID, Tds_Content);
                    log.debug("✴-数据库操作-控件-SQLPart：" + SQLPart);

                    // 两种情况:通过SQLID可以取到SQL, 如果无法取到判断是否是绑定的全局缓存SQL
                    if (!KHUtil.isNull(SQLPart)) {

                        doSQLRunCheck("控件绑定", SQLPart, "", s_DB_Type);

                    } else {
                        String sql_Cacheid = KHUtil.GetSFJV(in_Json, "cache");
                        List<Map<String, Object>> selectCaches = jt.queryForList("Select Sqlid, Dbpool, Sqltext, Sqlkey From Tab_Pubsqllist Where Sqlid = ?", sql_Cacheid);
                        if (selectCaches.size() > 0) {

                            // TODO 直接取全局的SQL 不拼接条件
                            SQLPart = selectCaches.get(0).get("Sqltext").toString();

                            doSQLRunCheck("控件全局缓存", SQLPart, "", s_DB_Type);

                        }
                    }

                } else {
                    String tmp_FindID = obj.toString();

                    // 如果长度是36则检查是否是组件ID
                    if (tmp_FindID.length() == 36) {
                        findComponent(tmp_FindID);
                    }
                    // log.debug("Json数据-key：" + key + " 值非JSONArray,JSONObject");
                }

            }
        }
        return re_Json.toString();
    }

    // 1-通过SQLID找到对象中对应的SQL片段
    public static String getSQLPart(String SQLID, String Tds_Content) {
        String res_SQLPart = "";
        try {
            JSONObject sql_Json = JSONObject.fromObject(Tds_Content);
            // 循环Loop
            Set<String> keySet = sql_Json.keySet();
            for (String key : keySet) {
                Object obj = sql_Json.get(key);

                // 根据类型识别是否继续递归
                if (key.equals(SQLID)) {
                    JSONObject sub = (JSONObject) obj;
                    res_SQLPart = KHUtil.GetSFJV(sub, "content");
                    break;
                }

            }
            log.debug("-通过SQLID找到SQL片段 结果✔:" + res_SQLPart);
            Dyn_SQLId = SQLID;

        } catch (Exception e) {
            log.error("-通过SQLID找到SQL片段 异常❌:" + e.getMessage());
        }
        return res_SQLPart;
    }

    // 2-对SQL进行参数,片段,运行检查
    public static void doSQLRunCheck(String SQL_Type, String check_SQL, String SQL_Key, String sql_DBType) {
        try {
            String run_SQL = parseSQLDSL(check_SQL, SQL_Key);
            log.debug("3-1-处理&拼接SQL片段-SQL_Type:" + SQL_Type + " run_SQL：" + run_SQL);

            run_SQL = parseSysPreset(run_SQL);
            log.debug("3-2-处理系统预设SQL变量-SQL_Type:" + SQL_Type + " run_SQL：" + run_SQL);

            run_SQL = parseSQLParam(run_SQL);
            log.debug("3-3-处理SQL片段变量-SQL_Type:" + SQL_Type + " run_SQL：" + run_SQL);

            // 对SQL运行测试是否报错 SQL特征码
            String Sql_Md5 = KHUtil.getMD5(Dyn_SQLId + check_SQL);
            String Check_Result = "未执行";
            String Check_Status = "0";
            String Check_Cost = "";
            try {
                if (sql_DBType.equals(s_DB_Type)) {
                    startTime = System.currentTimeMillis();
                    jt.execute(run_SQL);
                    Check_Result = "成功";
                    Check_Status = "1";
                    Check_Cost = String.valueOf(System.currentTimeMillis() - startTime);
                } else {
                    Check_Result = "忽略:数据库类型" + sql_DBType + " 非当前项目数据库类型SQL";
                    Check_Status = "2";

                }

            } catch (Exception e) {
                log.error("❌对SQL运行测试是否报错 SQL异常:" + e.getMessage());
                Check_Result = "错误:" + e.getMessage();
                Check_Status = "-1";
            } finally {
                int upd_Num = jt.update(upd_SQL, Dynid, Dynname, Dyntype, SQL_Type, check_SQL, run_SQL, Check_Result, Check_Status, sql_DBType, Dyn_Pageid, Dyn_CtlId, Dyn_CtlName, Dyn_SQLId, Check_Cost, Dynid2, Sql_Md5);

                // 如果没有更新成功则新增
                if (upd_Num <= 0) {
                    String Check_Guid = KHUtil.getRandomString(36);
                    upd_Num = jt.update(log_SQL, Check_Guid, Dynid, Dynid2, Dynname, Dyntype, Sql_Md5, SQL_Type, check_SQL, run_SQL, Check_Result, Check_Status, sql_DBType, Dyn_Pageid, Dyn_CtlId, Dyn_CtlName, Dyn_SQLId, Check_Cost);
                    log.debug("⛳-保存动态页面 Dynid2:" + Dynid2 + " Dynname:" + Dynname + " Pageid:" + Dyn_Pageid + " 新增DB:" + upd_Num);
                } else {
                    log.debug("⛳-保存动态页面 Dynid2:" + Dynid2 + " Dynname:" + Dynname + " Pageid:" + Dyn_Pageid + " 更新DB:" + upd_Num);
                }
            }

        } catch (Exception e) {
            log.error("", e);
        }
    }

    // 3-1-处理&拼接SQL片段
    public static String parseSQLDSL(String check_SQL, String sql_pKey) {
        try {
            List<String> res_SQLDSLs = get_SQLDSLs(check_SQL, "");

            for (int i = 0; i < res_SQLDSLs.size(); i++) {
                String dsl_Num = res_SQLDSLs.get(i).replace("{DSL_", "").replace("}", "");
                String sql_PartStr = KHUtil.GetMapV(SQL_DSL_Map, sql_pKey + "_" + dsl_Num);

                check_SQL = check_SQL.replace(res_SQLDSLs.get(i), sql_PartStr);

            }

        } catch (Exception e) {
            log.error("3-1-处理&拼接SQL片段 异常", e);
        }
        return check_SQL;
    }

    // 3-2-处理系统预设SQL变量
    public static String parseSysPreset(String check_SQL) {
        try {
            check_SQL = check_SQL.replaceAll("(?i)\\[epidtb]", "").replaceAll("(?i)\\[epid]", "").replaceAll("(?i)\\[staffid]", "SELITE").replaceAll("(?i)\\[rolegroupid]", "SYSTEM");

            check_SQL = check_SQL.replaceAll("(?i)\\{C_EPIDTB}", "").replaceAll("(?i)\\{C_EPID}", "").replaceAll("(?i)\\{C_GRP}", "SYSTEM").replaceAll("(?i)\\{C_BY}", "SELITE").replaceAll("(?i)\\{C_NOW}", "2024-08-16 00:00:00").replaceAll("(?i)\\{C_LANG}", "").replaceAll("(?i)\\{C_GUID}", KHUtil.getRandomString(36)).replaceAll("(?i)\\{C_SFID}", KHUtil.getRandomString(6)).replaceAll("(?i)\\{C_PAGE_START}", "1").replaceAll("(?i)\\{C_PAGE_END}", "100").replaceAll("(?i)\\{C_PAGE_SIZE}", "20");

            check_SQL = check_SQL.replaceAll("(?s)%B%.*?%E%", "");

            Pattern p = Pattern.compile("!\\((\\w+)\\)");
            Matcher matcher = p.matcher(check_SQL);
            while (matcher.find()) {
                int gc = matcher.groupCount();
                if (gc >= 1) {
                    String exp = matcher.group(1);
                    check_SQL = check_SQL.replaceAll("!\\(" + exp + "\\)", exp);
                }
            }
            Pattern pattern = Pattern.compile("#\\((.*?)\\)");
            Matcher match = pattern.matcher(check_SQL);
            while (match.find()) {
                int groupCount = match.groupCount();
                if (groupCount >= 1) {
                    String exp = match.group(1);
                    check_SQL = check_SQL.replaceAll("#\\(" + exp + "\\)", "");
                }
            }
        } catch (Exception e) {
            log.error("3-2-处理系统预设SQL变量 异常", e);
        }
        return check_SQL;
    }

    // 3-3-处理SQL片段变量
    public static String parseSQLParam(String check_SQL) {
        try {

            //循环替换50次
            for (int j = 0; j < 100; j++) {
                String str2 = "@{C" + j + "}N";
                String str3 = "@{C" + j + "}S";
                String str4 = "@{C" + j + "}L";
                String str5 = "@{C" + j + "}@";
                String str6 = "@{C" + j + "}D";
                String str7 = "to_date(@{C" + j + "}S";
                String str8 = "@{C" + j + "}";
                check_SQL = check_SQL.replace(str7, "to_date('2099-01-01 00:00:00'").replace(str2, "999").replace(str3, "'" + KHUtil.getRandomString(6) + "'").replace(str4, "'#####1','#####2'").replace(str5, "Variable_Table").replace(str6, "'2099-01-01 00:00:00'").replace(str8, "'@{C" + j + "}'");

            }

        } catch (Exception e) {
            log.error("3-3-处理SQL片段变量 异常", e);
        }
        return check_SQL;
    }

    // 获取{DSL_ List
    public static List<String> get_SQLDSLs(String strInfo, String rgex) {

        List<String> DSLLists = new ArrayList<>();

        String patternString1 = KHUtil.isNull(rgex) ? "(\\{DSL_\\d})" : rgex;
        Pattern pattern = Pattern.compile(patternString1);
        Matcher matcher = pattern.matcher(strInfo);

        while (matcher.find()) {
            String cn_Key = matcher.group();
            DSLLists.add(cn_Key);
        }

        Iterator<String> iterator = DSLLists.iterator();
        while (iterator.hasNext()) {
            String next = iterator.next();

            if (!next.startsWith("{DSL_")) {
                iterator.remove();
            }
        }

        // 返回
        return DSLLists;
    }

    // 获取clearDsl List
    public static List<String> get_ClearDSLs(String strInfo, String rgex) {

        List<String> DSLLists = new ArrayList<>();

        String patternString1 = KHUtil.isNull(rgex) ? "(clearDsl\\('\\w+')" : rgex;
        Pattern pattern = Pattern.compile(patternString1);
        Matcher matcher = pattern.matcher(strInfo);

        while (matcher.find()) {
            String cn_Key = matcher.group();
            DSLLists.add(cn_Key);
        }

        Iterator<String> iterator = DSLLists.iterator();
        while (iterator.hasNext()) {
            String next = iterator.next();

            if (!next.startsWith("clearDsl")) {
                iterator.remove();
            }
        }

        // 返回
        return DSLLists;
    }

    // 查找组件
    private static void findComponent(String find_ID) {

        String findComponent_SQL = "Select Dynid2, Dynname From Tab_Dyn Where Dyntype = 1 And Dynid = ?";
        List<Map<String, Object>> selectExits = jt.queryForList(findComponent_SQL, find_ID);
        if (selectExits.size() > 0) {

            String Comp_Dynid2 = KHUtil.GetMapV(selectExits.get(0), "Dynid2");
            String Comp_Dynname = KHUtil.GetMapV(selectExits.get(0), "Dynname");

            int upd_Num = jt.update(comp_Upd_SQL, Dynid, Dynname, Dyntype, Dyn_Pageid, Comp_Dynname, Dynid2, Comp_Dynid2);

            // 如果没有更新成功则新增
            if (upd_Num <= 0) {
                String Check_Guid = KHUtil.getRandomString(36);
                upd_Num = jt.update(comp_Log_SQL, Check_Guid, Dynid, Dynid2, Dynname, Dyntype, Dyn_Pageid, Comp_Dynid2, Comp_Dynname);
                log.debug("⛳-保存页面组件 Dynid2:" + Dynid2 + " Dynname:" + Dynname + " Pageid:" + Dyn_Pageid + " Comp_Dynid2:" + Comp_Dynid2 + "/" + Comp_Dynname + " 新增DB:" + upd_Num);
            } else {
                log.debug("⛳-保存页面组件 Dynid2:" + Dynid2 + " Dynname:" + Dynname + " Pageid:" + Dyn_Pageid + " Comp_Dynid2:" + Comp_Dynid2 + "/" + Comp_Dynname + " 更新DB:" + upd_Num);
            }

        }
    }

}